import type { PositionAnalysisSchema } from "@/types/account.types";
import {
  renderNumberCell,
  renderSymbolCell,
  renderTextCell
} from "@/utils/cell";
import { useBreakpointQuery } from "@/utils/device";
import { computed, ref } from "vue";

export const usePositionAnalysis = (forceCompact = false) => {
  const expandRowKeys = ref<string[]>([]);

  const { isSmUp, isMdUp } = useBreakpointQuery();

  const tableSize = computed(() => {
    if (forceCompact) {
      return "small";
    }
    if (isMdUp()) {
      return "default";
    }
    return "small";
  });

  const getPositionAnalysisColumns = () => {
    const isSmallUp = forceCompact ? false : isSmUp();
    const isMediumUp = forceCompact ? false : isMdUp();

    const labelDirection = isMediumUp ? "方向" : isSmallUp ? "LS" : "";
    const labelLongGamma = isMediumUp ? "Long-γ" : isSmallUp ? "L-γ" : "γ+";
    const labelShortGamma = isMediumUp ? "Short-γ" : isSmallUp ? "S-γ" : "γ-";
    const labelCost = isMediumUp ? "开仓成本" : "成本";
    const labelPnlByCost = isMediumUp ? "逐笔盈亏" : "逐笔";
    const labelIntrinsicValue = isMediumUp ? "内在价值" : "内在";
    const labelTimeValue = isMediumUp ? "时间价值" : "时间";
    const labelMarketValue = isMediumUp ? "期权市值" : "市值";

    const widthUnderlyingSymbol = isMediumUp ? 70 : 50;
    const labelMinWidth = isMediumUp ? 120 : 90;

    const positionAnalysisColumns: TableColumnList = [
      {
        label: "",
        prop: "underlying_symbol",
        width: widthUnderlyingSymbol,
        formatter: (row: {
          underlying_symbol: string;
          is_summary_row: boolean;
        }) =>
          renderTextCell(
            row.underlying_symbol,
            row.is_summary_row ? "font-bold" : ""
          )
      },
      {
        label: "合约",
        prop: "symbol",
        align: "left",
        minWidth: labelMinWidth,
        formatter: (row: { symbol?: string; is_summary_row?: boolean }) =>
          row.is_summary_row || !row.symbol
            ? renderTextCell("")
            : renderSymbolCell(row.symbol)
      },

      {
        label: "Delta",
        prop: "delta",
        align: "right",
        minWidth: 90,
        formatter: (row: { delta: number; is_summary_row: boolean }) =>
          typeof row.delta === "undefined"
            ? renderTextCell("")
            : renderNumberCell(
                row.delta,
                row.is_summary_row ? 2 : 4,
                false,
                true,
                false,
                row.is_summary_row ? "font-bold" : ""
              )
      },
      {
        label: labelLongGamma,
        prop: "long_gamma",
        align: "right",
        minWidth: 110,
        formatter: (row: { long_gamma?: number; is_summary_row: boolean }) =>
          typeof row.long_gamma === "undefined"
            ? renderTextCell("")
            : renderNumberCell(
                row.long_gamma || 0,
                row.is_summary_row ? 4 : 6,
                false,
                true,
                false,
                row.is_summary_row ? "font-bold" : ""
              )
      },
      {
        label: labelShortGamma,
        prop: "short_gamma",
        align: "right",
        minWidth: 110,
        formatter: (row: { short_gamma?: number; is_summary_row: boolean }) =>
          typeof row.short_gamma === "undefined"
            ? renderTextCell("")
            : renderNumberCell(
                row.short_gamma || 0,
                row.is_summary_row ? 4 : 6,
                false,
                true,
                false,
                row.is_summary_row ? "font-bold" : ""
              )
      },
      {
        label: labelDirection,
        prop: "direction",
        minWidth: 55,
        align: "center",
        formatter: (row: { direction: string }) =>
          renderTextCell(
            row.direction,
            row.direction === "多"
              ? "text-text_red_text"
              : "text-text_green_text"
          )
      },
      {
        label: "数量",
        prop: "volume",
        align: "right",
        minWidth: 55,
        formatter: (row: { volume: number; is_summary_row: boolean }) =>
          row.is_summary_row || typeof row.volume === "undefined"
            ? renderTextCell("")
            : renderNumberCell(row.volume, 0, false, false)
      },
      {
        label: labelCost,
        prop: "cost",
        align: "right",
        minWidth: 100,
        formatter: (row: { cost: number }) =>
          renderNumberCell(row.cost, 2, false, false)
      },
      {
        label: "最新价",
        prop: "last_price",
        align: "right",
        minWidth: 100,
        formatter: (row: { last_price?: number; is_summary_row?: boolean }) =>
          row.is_summary_row || typeof row.last_price === "undefined"
            ? renderTextCell("")
            : renderNumberCell(row.last_price, 2, false, false)
      },
      {
        label: "标的价",
        prop: "underlying_last_price",
        align: "right",
        minWidth: 100,
        formatter: (row: {
          option_underlying_last_price?: number;
          is_summary_row?: boolean;
        }) =>
          row.is_summary_row ||
          typeof row.option_underlying_last_price === "undefined"
            ? renderTextCell("")
            : renderNumberCell(
                row.option_underlying_last_price,
                2,
                false,
                false
              )
      },
      {
        label: labelPnlByCost,
        prop: "pnl_by_cost",
        align: "right",
        minWidth: 100,
        formatter: (row: { pnl_by_cost: number; is_summary_row?: boolean }) =>
          typeof row.pnl_by_cost === "undefined"
            ? renderTextCell("")
            : renderNumberCell(
                row.pnl_by_cost,
                1,
                false,
                true,
                false,
                row.is_summary_row ? "font-bold" : ""
              )
      },
      {
        label: labelIntrinsicValue,
        prop: "option_intrinsic_value",
        align: "right",
        minWidth: 100,
        formatter: (row: { option_intrinsic_value: number }) =>
          renderNumberCell(row.option_intrinsic_value, 1, false, true)
      },
      {
        label: labelTimeValue,
        prop: "option_time_value",
        align: "right",
        minWidth: 100,
        formatter: (row: { option_time_value: number }) =>
          renderNumberCell(row.option_time_value, 1, false, true)
      },
      {
        label: labelMarketValue,
        prop: "option_market_value",
        align: "right",
        minWidth: 100,
        formatter: (row: { option_market_value: number }) =>
          renderNumberCell(row.option_market_value, 1, false, true)
      }
    ];

    return positionAnalysisColumns;
  };

  const positionAnalysisColumns = computed(() => getPositionAnalysisColumns());

  const getRowKey = (row: PositionAnalysisSchema) => {
    return `${row.underlying_symbol}-${row.symbol}-${row.direction}`;
  };

  const expandAll = (rows: Array<PositionAnalysisSchema>) => {
    if (!Array.isArray(rows)) {
      expandRowKeys.value = [];
      return;
    }
    expandRowKeys.value = rows.map(row => getRowKey(row));
  };

  const collapseAll = () => {
    expandRowKeys.value = [];
  };

  const handleExpandChange = (
    row: PositionAnalysisSchema,
    expanded: boolean
  ) => {
    if (expanded) {
      expandRowKeys.value.push(getRowKey(row));
    } else {
      expandRowKeys.value = expandRowKeys.value.filter(
        symbol => symbol !== getRowKey(row)
      );
    }
  };

  return {
    tableSize,
    positionAnalysisColumns,
    expandRowKeys,
    handleExpandChange,
    expandAll,
    collapseAll
  };
};
